using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;


//[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.UserDefined, MaxByteSize=256)]
public struct VectorMin : IBinarySerialize
{
    private double[] min;

    public void Init()
    {
        min = null;
    }

    public void Accumulate(SqlBinary Value)
    {
        double[] vec = Elte.SqlSpIdx.Converters.VectorConverter.ToArray(Value);

        if (min == null)
        {
            min = new double[vec.Length];
            for (int k = 0; k < min.Length; k++)
                min[k] = double.MaxValue;
        }

        for (int k = 0; k < vec.Length; k++)
            min[k] = Math.Min(min[k], vec[k]);
    }

    public void Merge(VectorMin Group)
    {
        if (min == null)
        {
            min = new double[Group.min.Length];
            for (int k = 0; k < min.Length; k++)
                min[k] = double.MaxValue;
        }

        for (int k = 0; k < Group.min.Length; k++)
            min[k] = Math.Min(min[k], Group.min[k]);
    }

    public SqlBinary Terminate()
    {
        return new SqlBinary(Elte.SqlSpIdx.Converters.VectorConverter.ToBinary(min));
    }

    #region IBinarySerialize Members

    public void Read(System.IO.BinaryReader r)
    {
        int length = r.ReadInt32();
        min = Elte.SqlSpIdx.Converters.VectorConverter.ToArray(r.ReadBytes(length * sizeof(double) + sizeof(int) + sizeof(int)));
    }

    public void Write(System.IO.BinaryWriter w)
    {
        w.Write(min.Length);
        w.Write(Elte.SqlSpIdx.Converters.VectorConverter.ToBinary(min));
    }

    #endregion
}
